package cn.itcast.wanxinp2p.consumer.service.impl;


import cn.itcast.wanxinp2p.common.DTO.account.AccountRegisterDTO;
import cn.itcast.wanxinp2p.common.DTO.comsumer.ConsumerRegisterDTO;

import cn.itcast.wanxinp2p.common.domain.CodePrefixCode;
import cn.itcast.wanxinp2p.common.exception.BusinessException;
import cn.itcast.wanxinp2p.common.util.CodeNoUtil;
import cn.itcast.wanxinp2p.consumer.agent.DemoFeign;
import cn.itcast.wanxinp2p.consumer.entity.Consumer;
import cn.itcast.wanxinp2p.consumer.exception.ConsumerErrorCode;
import cn.itcast.wanxinp2p.consumer.mapper.ConsumerMapper;
import cn.itcast.wanxinp2p.consumer.service.ConsumerService;
import lombok.extern.slf4j.Slf4j;

import org.dromara.hmily.annotation.Hmily;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class ConsumerServiceImpl implements ConsumerService {


    @Autowired
    private ConsumerMapper consumerMapper;


    @Autowired
    private DemoFeign demoFeign;

    @Override
    public Integer checkMobile(String mobile) {
        //根据手机号查询用户，存在返回1 不存在返回0
        return consumerMapper.selectByMobile(mobile);
    }
    
    @Override
    @Hmily(confirmMethod = "confirmRegister", cancelMethod = "cancelRegister")
    public void register(ConsumerRegisterDTO consumerRegisterDTO) {

        //1、检测是否已注册，如果已经注册，则抛出 ConsumerErrorCode.E_140107 异常
        Integer integer = consumerMapper.selectByMobile(consumerRegisterDTO.getMobile());

            if (integer==1){
                throw new BusinessException(ConsumerErrorCode.E_140107);
            }

        //2、如果用户没有注册，则保存该用户数据 到 consumer 表中

        Consumer consumer = new Consumer();
        /*转移数据*/
        BeanUtils.copyProperties(consumerRegisterDTO,consumer);
        /*通过uuID生成账号*/
        consumer.setUsername(CodeNoUtil.getNo(CodePrefixCode.CODE_NO_PREFIX));
        /*通过uuID生成编码*/
        consumer.setUserNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX));
        /*设置银行卡*/
        consumer.setIsBindCard(0);

        consumerMapper.save(consumer);
        //3、并通过Feign远程调用 统一账号服务 实现 账号的保存

        consumerRegisterDTO.setUsername(consumer.getUsername());

        AccountRegisterDTO accountRegisterDTO = new AccountRegisterDTO();
        BeanUtils.copyProperties(consumerRegisterDTO,accountRegisterDTO);

        System.out.println(accountRegisterDTO);
        demoFeign.register(accountRegisterDTO);

//        int a=1/0;

    }

    /*?????*/
    public void confirmRegister(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("execute confirmRegister");

    }
    public void cancelRegister(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("execute cancelRegister");
        /*根据手机号删除数据*/


        consumerMapper.deleteByMobile(consumerRegisterDTO.getMobile());

        //TODO 删除用户
    }

}